package com.example.service;

import com.example.entity.PageResult;
import com.example.entity.User;
import com.example.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 任务一：根据用户名查询用户及其角色
     */
    public User getUserWithRolesByUsername(String username) {
        return userMapper.selectUserWithRolesByUsername(username);
    }

    /**
     * 任务三：根据条件搜索用户（不分页）
     */
    public List<User> searchUsers(String username, String email, Integer status) {
        return userMapper.selectUsersWithRolesAndMenusByCondition(username, email, status);
    }

    /**
     * 任务三：根据条件分页查询用户
     */
    public PageResult<User> searchUsersByPage(String username, String email, Integer status, int pageNum, int pageSize) {
        // 计算偏移量
        int offset = (pageNum - 1) * pageSize;
        
        // 查询当前页数据
        List<User> records = userMapper.selectUsersWithRolesAndMenusByConditionPage(
                username, email, status, offset, pageSize);
        
        // 查询总数
        int total = userMapper.countUsersByCondition(username, email, status);
        
        // 构建分页结果
        return new PageResult<>(total, records, pageNum, pageSize);
    }

    /**
     * 统计符合条件的用户数量
     */
    public int countUsers(String username, String email, Integer status) {
        return userMapper.countUsersByCondition(username, email, status);
    }
}